package io.bluerain.storage.ui;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

import io.bluerain.storage.R;

/**
 * Created by foredawn on 15-9-13.
 * SharePreferences基本用法
 */
public class SharedPreferencesActivity extends Activity {

    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    Context otherAppContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shared_preferences_activity);
        preferences = getSharedPreferences("share", Context.MODE_WORLD_READABLE);
        editor = preferences.edit();
        try {
            otherAppContext = createPackageContext("io.bluerain.storage", Context.CONTEXT_IGNORE_SECURITY);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void write(View source) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
        String nowDate = sf.format(new Date());
        int random = (int) (Math.random() * 100);
        editor.putString("date", nowDate);
        editor.putInt("random", random);
        editor.commit();
        Toast.makeText(this, "储存成功", Toast.LENGTH_SHORT).show();
    }

    public void read(View source) {

        String date = preferences.getString("date", null);
        int random = preferences.getInt("random", -1);
        Toast.makeText(this, date + ":" + random, Toast.LENGTH_LONG).show();
    }

    public void readOther(View source) {
        SharedPreferences op = otherAppContext.getSharedPreferences("share", Context.MODE_WORLD_READABLE);
        Toast.makeText(this, "找到随机数:" + op.getInt("random", -1), Toast.LENGTH_SHORT).show();

    }
}
